<script lang="ts" setup>
  import { ref, onMounted, onUnmounted, watch, nextTick } from 'vue';
  import * as echarts from 'echarts/core';
  const props = defineProps({
    dataBar1: { type: Object as () => any, required: true },
    dataBar2: { type: Object as () => any, default: [] },
    dataBar3: { type: Object as () => any, default: [] },
    dataBar4: { type: Object as () => any, default: [] },
    dataLine1: { type: Object as () => any, default: [] },
    dataLine2: { type: Object as () => any, default: [] },
    datax: { type: Object as () => any, required: true },
    yAxisName: { type: Object as () => any, default: [] },
    barName: { type: Object as () => any, default: [] },
    lineName: { type: Object as () => any, default: [] },
    formatVal: { type: Object as () => any, default: [] },
    title: { type: String, default: '' },
    legendPos: { type: Number, default: 5 },
    min: { type: Number, default: 0 },
    max: { type: Number, default: 100 },
    config: { type: Object as () => any, required: true },
  });

  const chartRef = ref<HTMLElement | null>(null);
  let chartInstance: echarts.ECharts | null = null;

  const option = ref<any>({
    title: {
      text: props.title, // 图表标题
      left: 'center', // 标题居中
      textStyle: {
        fontSize: 16,
        fontWeight: 'bold',
      },
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        // type: 'cross',
        crossStyle: {
          color: '#999',
        },
      },
      backgroundColor: 'rgba(22, 27, 88, 0.90)',
      borderColor: 'rgba(65, 164, 230, 1)',
      borderWidth: 1,
      textStyle: {
        color: '#FFFFFF',
        fontSize: 14,
        fontWeight: 400,
        align: 'left',
      },
      padding: 10,
      extraCssText: 'text-align:left',
      appendToBody: true,
      position: function (point: any) {
        return [point[0], point[1] + 20];
      },
    },
    legend: {
      data: [...props.barName, ...props.lineName],
      bottom: '5%',
      textStyle: {
        color: '#fff',
        fontSize: 12,
      },
      left: 'center',
      itemWidth: 16,
      itemHeight: 10,
      itemGap: 30,
      selectedMode: false,
      show: false,
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '8%',
      containLabel: true,
    },
    xAxis: {
      type: 'category',
      data: props.datax ?? [], // X 轴类目
      axisLine: { lineStyle: { color: '#fff' } },
      axisLabel: { color: '#fff' },
    },
    yAxis: [
      {
        // scale: true,
        min: props.min,
        max: props.max,
        type: 'value',
        name: props.yAxisName[0],
        nameTextStyle: {
          color: '#fff',
          padding: [0, 18, 0, 0],
        },
        axisLabel: {
          formatter: '{value}',
          color: '#fff',
        },
        axisLine: {
          show: false,
        },
        axisTick: {
          show: false,
        },
        splitLine: { show: true, lineStyle: { type: 'dotted' } },
      },
      {
        type: 'value',
        name: props.yAxisName[1],
        // scale: true,
        position: 'right', // 右侧 Y 轴
        axisLabel: {
          formatter: '{value}' + '%',
          color: '#fff',
        },
        axisLine: {
          show: false,
        },
        axisTick: {
          show: false,
        },
        splitLine: {
          show: false,
          lineStyle: {
            type: 'dashed',
            color: '#ccc',
          },
        },
      },
    ],
    series: [
      // 第一个柱状图的钻石顶部
      {
        z: 2,
        name: props.barName[0] ?? '',
        type: 'pictorialBar',
        symbolPosition: 'end',
        data: props.dataBar1 ?? [],
        symbol: 'diamond',
        symbolOffset: props.config.diamond.offset1,
        symbolSize: props.config.diamond.size,
        yAxisIndex: 0,
        itemStyle: {
          color: {
            type: 'linear',
            x: 0,
            x2: 1,
            y: 0,
            y2: 0,
            colorStops: [
              { offset: 0, color: 'rgba(129, 202, 254, 1)' },
              { offset: 1, color: 'rgba(59, 170, 250, 1)' },
            ],
          },
        },
        tooltip: {
          show: false,
        },
      },
      // 第一个柱状图的柱体（功率实际值）
      {
        z: 1,
        name: props.barName[0] ?? '',
        type: 'bar',
        barWidth: props.config.barWidth,
        barGap: props.config.barGap,
        data: props.dataBar1 ?? [],
        yAxisIndex: 0,
        itemStyle: {
          color: {
            type: 'linear',
            x: 0,
            x2: 1,
            y: 0,
            y2: 0,
            colorStops: [
              { offset: 0, color: 'rgba(20, 67, 133, 1)' },
              { offset: 0.5, color: 'rgba(59, 170, 250, 1)' },
              { offset: 0.5, color: 'rgba(16, 79, 149, 1)' },
              { offset: 1, color: 'rgba(23, 98, 182, 1)' },
            ],
          },
        },
      },
      // 第二个柱状图的钻石顶部（电机扭矩实际值）
      {
        z: 2,
        name: props.barName[1] ?? '',
        type: 'pictorialBar',
        symbolPosition: 'end',
        data: props.dataBar2 ?? [],
        symbol: 'diamond',
        symbolOffset: props.config.diamond.offset2,
        symbolSize: props.config.diamond.size,
        yAxisIndex: 0,
        itemStyle: {
          color: {
            type: 'linear',
            x: 0,
            x2: 1,
            y: 0,
            y2: 0,
            colorStops: [
              { offset: 0, color: 'rgba(149, 251, 244, 1)' },
              { offset: 1, color: 'rgba(62, 207, 247, 1)' },
            ],
          },
        },
        tooltip: {
          show: false,
        },
      },
      // 第二个柱状图的柱体（电机扭矩实际值）
      {
        z: 1,
        name: props.barName[1] ?? '',
        type: 'bar',
        barWidth: props.config.barWidth,
        data: props.dataBar2 ?? [],
        yAxisIndex: 0,
        itemStyle: {
          color: {
            type: 'linear',
            x: 0,
            x2: 1,
            y: 0,
            y2: 0,
            colorStops: [
              { offset: 0, color: 'rgba(28, 121, 153, 1)' },
              { offset: 0.5, color: 'rgba(69, 207, 216, 1)' },
              { offset: 0.5, color: 'rgba(37, 149, 180, 1)' },
              { offset: 1, color: 'rgba(18, 91, 111, 1)' },
            ],
          },
        },
      },
      {
        name: props.barName[2] ?? '',
        type: 'bar',
        barWidth: 15,
        data: props.dataBar3 ?? [],
        yAxisIndex: 0,
        itemStyle: {
          color: '#f56c6c',
          borderRadius: [8, 8, 8, 8],
          opacity: 0.9,
        },
      },
      {
        name: props.barName[3] ?? '',
        type: 'bar',
        barWidth: 15,
        data: props.dataBar4 ?? [],
        yAxisIndex: 0,
        itemStyle: {
          color: '#20a0ff',
          borderRadius: [8, 8, 8, 8],
          opacity: 0.9,
        },
      },
      {
        name: props.lineName[0] ?? '',
        type: 'line',
        data: props.dataLine1 ?? [],
        yAxisIndex: 1,
        symbol: 'circle',
        symbolSize: 4,
        itemStyle: {
          color: 'rgba(235, 163, 63, 1)',
        },
      },
      {
        name: props.lineName[1] ?? '',
        type: 'line',
        data: props.dataLine2 ?? [],
        yAxisIndex: 1,
        symbol: 'circle',
        symbolSize: 4,
        itemStyle: {
          color: '#91cc75',
        },
      },
    ],
  });

  const initCharts = () => {
    try {
      // formatterOption();
      if (chartRef.value && !chartInstance) {
        chartInstance = echarts.init(chartRef.value);
        chartInstance?.setOption(option.value, true);
      }
    } catch (error) {
      console.error('图表初始化失败:', error);
    }
  };

  const updateChart = () => {
    try {
      formatterOption();
      option.value.title.text = props.title;
      option.value.xAxis.data = Array.isArray(props.datax) ? props.datax : [];
      if (chartInstance) {
        chartInstance.setOption(option.value, true);
      }
    } catch (error) {
      console.error('更新图表失败:', error);
    }
  };

  const formatterOption = () => {
    const series = [];
    const allSeries = option.value.series;

    // dataBar1 钻石顶部和柱体（索引0和1）
    if (allSeries[0]) {
      allSeries[0].data = Array.isArray(props.dataBar1) ? props.dataBar1 : [];
      series.push(allSeries[0]);
    }
    if (allSeries[1]) {
      allSeries[1].data = Array.isArray(props.dataBar1) ? props.dataBar1 : [];
      series.push(allSeries[1]);
    }

    // dataBar2 钻石顶部和柱体（索引2和3）
    if (props.dataBar2 && props.dataBar2.length > 0) {
      if (allSeries[2]) {
        allSeries[2].data = props.dataBar2;
        series.push(allSeries[2]);
      }
      if (allSeries[3]) {
        allSeries[3].data = props.dataBar2;
        series.push(allSeries[3]);
      }
    }

    // dataBar3（索引4）
    if (props.dataBar3 && props.dataBar3.length > 0) {
      if (allSeries[4]) {
        allSeries[4].data = props.dataBar3;
        series.push(allSeries[4]);
      }
    }

    // dataBar4（索引5）
    if (props.dataBar4 && props.dataBar4.length > 0) {
      if (allSeries[5]) {
        allSeries[5].data = props.dataBar4;
        series.push(allSeries[5]);
      }
    }

    // dataLine1（索引6）
    if (props.dataLine1 && props.dataLine1.length > 0) {
      if (allSeries[6]) {
        allSeries[6].data = props.dataLine1;
        series.push(allSeries[6]);
      }
    }

    // dataLine2（索引7）
    if (props.dataLine2 && props.dataLine2.length > 0) {
      if (allSeries[7]) {
        allSeries[7].data = props.dataLine2;
        series.push(allSeries[7]);
      }
    }

    option.value.series = series;
    option.value.yAxis[0].name = props.yAxisName[0];
    option.value.yAxis[1].name = props.yAxisName[1];
    let isLegend = [...props.barName, ...props.lineName].length > 1;
    if (isLegend) {
      option.value.legend.data = [...props.barName, ...props.lineName];
      option.value.legend.show = true;
      option.value.grid.bottom = '20%';
    } else {
      option.value.legend.show = false;
      option.value.grid.bottom = '8%';
    }
    option.value.title.text = props.title;
  };

  onMounted(() => {
    // 确保在 DOM 加载完成后更新图表
    setTimeout(() => {
      nextTick(() => {
        initCharts();
      });
    }, 100);

    // 添加窗口大小变化监听
    window.addEventListener('resize', handleResize);
  });

  onUnmounted(() => {
    // 移除窗口大小变化监听
    window.removeEventListener('resize', handleResize);
    chartInstance?.dispose();
  });

  watch(
    () => [props.datax, props.dataBar1, props.dataBar2, props.dataBar3, props.dataBar4, props.dataLine1, props.dataLine2, props.title],
    () => updateChart(),
    { deep: true }
  );

  defineExpose({
    updateChart, // 暴露方法到父组件
  });

  // 窗口大小变化处理
  const handleResize = () => {
    nextTick(() => {
      chartInstance?.resize();
    });
  };
</script>
<template>
  <div ref="chartRef" class="chart-container"></div>
</template>

<style scoped>
  .chart-container {
    width: 100%;
    height: 100%;
  }
</style>
